package pers.zc.activiti.suanfa.mulushu;

import org.activiti.engine.impl.util.json.JSONArray;
import pers.zc.activiti.entity.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Annotion:
 * @ClassName: MuluDataimpl
 * @Author: Lin Fuyuan
 * @Date: 2019/9/19  9:01
 * @Version: 1.0
 */
public class Mulu {
    private static List<String>  url =null;
    static{
        url = new ArrayList<>();

        url.add("/a");
        url.add("/a");
        url.add("/a");
        url.add("/b");
        url.add("/b");
    }
    /**
     *
     */
    public static void main(String[] args){
        System.out.println(url);
        List<TreeNode> nodeList = new ArrayList<>();
        for (String s : url) {
            TreeNode node = new TreeNode();
            node.setUrl(s);
            nodeList.add(node);
        }

        //获取树
        JSONArray aar = new JSONArray(nodeList);
//        System.out.println(aar.toString());
        System.out.println("------------");
        List<TreeNode> treeNodes = listToTree(nodeList);
        JSONArray array = new JSONArray(treeNodes);
        System.out.println(array.toString());

    }


    public static List<TreeNode> listToTree(List<TreeNode> list) {
        List<TreeNode> treeList = new ArrayList<TreeNode>();
        for (TreeNode tree : list) {
            //首先判断找根目录,根目录长度
            if (tree.getUrl().split("/").length == 2) {
                treeList.add(findChildren(tree, list));
            }
        }
        return treeList;
    }

    private static TreeNode findChildren(TreeNode tree, List<TreeNode> list) {
        for (TreeNode node : list) {
            String url = node.getUrl().substring(0,node.getUrl().lastIndexOf("/") );
            if (url.equals(tree.getUrl()) ) {
                if (tree.getNodeList() == null) {
                    tree.setNodeList(new ArrayList<TreeNode>());

                }
                tree.getNodeList().add(findChildren(node, list));
            }
        }
        return tree;
    }


}
